/***********************************************
*	名称:日志
*	说明:日志打印工具(打印,写入文件,转发)
*	作者:钱纯净
************************************************/
package lgs

import (
	"fmt"
	"log"
	"os"
)

type ILogs interface {
	Level(int) ILogs              //日志位置层级
	WriteToFilePath(string) ILogs //日志输出文件路径
	WriteToFile(b ...bool) ILogs  //是否输出到文件
	//Tcp(string, string) ILogs     //是否建立tcp连接
	Write(string, []byte) error //写入到文件
	ShowColor(...bool) ILogs    //颜色(测试阶段)

	Test(...interface{})
	Info(...interface{})
	Error(...interface{})
	Err(...interface{})
	Debug(...interface{})
}

type Lgs struct {
	path  string //文件输出路径
	cPath bool   //文件夹是否创建
	level int    //层级,默认3级
	write bool   //输出到文件
	color bool   //颜色(有些显示不了,打印出其它内容)
	//tcp    *conn  //*LogTcp //同步日志
	//tcpKey string //推送项目key

	//map[string]
}

func New() ILogs {
	data := &Lgs{
		level: 4,
		path:  "./output/lgs",
		write: false,
	}
	return data
}

//func (this *Lgs) Tcp(ip, tcpkey string) ILogs {
//	//this.tcpKey = tcpkey
//	//go this.newTcp(ip)
//	return this
//}

func (this *Lgs) Level(n int) ILogs {
	this.level = n + 4
	return this
}

func (this *Lgs) WriteToFilePath(s string) ILogs {
	this.path = s
	return this
}

func (this *Lgs) WriteToFile(b ...bool) ILogs {
	if len(b) > 0 && !b[0] {
		this.write = false
	} else {
		this.write = true
		//创建文件夹
		this.create()
	}
	return this
}

func (this *Lgs) ShowColor(b ...bool) ILogs {
	this.color = !(len(b) > 0 && !b[0])
	return this
}

//--------------------------------------------

func (this *Lgs) Test(s ...interface{}) { this.do(PTest, Blue, s...) }

func (this *Lgs) Err(s ...interface{}) { this.do(PErr, Red, s...) }

func (this *Lgs) Error(s ...interface{}) { this.do(PErr, Red, s...) }

func (this *Lgs) Info(s ...interface{}) { this.do(PInfo, Cyan, s...) }

func (this *Lgs) Debug(s ...interface{}) { this.do(PDebug, Yellow, s...) }

//---------------------------------------

func (this *Lgs) do(prefix string, color int, s ...interface{}) {
	//新建文件写入
	w := newWrite(prefix, this.level, s...)
	//打印到控制台
	this.toConsole(color, w.string())
	//输出到文件
	this.toFile(prefix, w.data())
	//推送
	//this.toTcp(w.string())
}

//---------------------------------------------

//输出到控制台
func (this *Lgs) toConsole(color int, s string) {
	if color != 0 && this.color {
		s = SetColor(color, s)
	}
	fmt.Println(s)
}

//输出到文件
func (this *Lgs) toFile(prefix string, bs []byte) {
	if this.write {
		if err := this.Write(prefix, bs); err != nil {
			log.Println("写入文件错误:", err)
		}
	}
}

//ToFile 日志记录到文件
func (this *Lgs) Write(s string, content []byte) error {
	name := this.fileName(s)
	logfile, err := os.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_APPEND, os.ModeAppend|os.ModePerm)
	if err != nil {
		return err
	}
	defer logfile.Close()
	_, err = logfile.Write(content)
	return err
}
